package cn.stronglink.assetmanage.business.inventory.presenter;

import android.app.Dialog;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.List;

import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.inventory.model.InventoryModel;
import cn.stronglink.assetmanage.business.inventory.view.InventoryView;
import cn.stronglink.assetmanage.entity.Inventory;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by chencongcong on 2018/6/18.
 */

public class InventoryPresenter implements InventoryModel.onInventoryDataListener{
    private InventoryView inventoryView;
    private InventoryModel inventoryModel;

    public InventoryPresenter(InventoryView inventoryView, InventoryModel inventoryModel) {
        this.inventoryView = inventoryView;
        this.inventoryModel = inventoryModel;
        this.inventoryModel.setOnInventoryDataListener(this);
    }

    public void getInventoryData(){
        inventoryView.showProgressDialog(MyApplication.APP_CONTEXT.getString(R.string.geting_inventory_data));
        inventoryModel.getInventoryData();
    }

    @Override
    public void onFailure(Call call, IOException ex) {
        inventoryView.hideProgressDialog();
        inventoryView.showToast(ex.getMessage());
    }

    @Override
    public void onResponse(Call call, Response response) {
        try {
            inventoryView.hideProgressDialog();
            if (response.isSuccessful()) {
                if (response.code() == 200) {
                    String resultJson = null;
                    try {
                        resultJson = response.body().string();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (resultJson != null) {
                        inventoryModel.saveInventoryData(resultJson);
                        inventoryView.refreshView();
                    } else {
                        inventoryView.showToast(MyApplication.APP_CONTEXT.getString(R.string.get_no_data));
                    }
                } else {
                    inventoryView.showToast(response.message());
                }
            } else {
                inventoryView.showToast(MyApplication.APP_CONTEXT.getString(R.string.get_data_fail));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
